package jeye.lcdui;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import jeye.client.thread.EventsLoaderThread;
import jeye.client.thread.ThreadListener;
import jeye.lcdui.util.HttpServiceSupport;
import jeye.lcdui.util.ScreenFactorySupport;
import jeye.midlet.ApplicationController;
import jeye.midlet.ScreenType;
import jeye.util.CacheKey;
import jeye.util.HttpConnector;

public class EventsList extends List implements CommandListener, ThreadListener, ScreenFactorySupport, HttpServiceSupport {

	private ApplicationController controller;
	
	private HttpConnector connector;
	
	private EventsLoaderThread eventsLoader;
	
	private Command backCommand = new Command("Wstecz", Command.BACK, 2);

	public EventsList() {
		super("Zapisane zdarzenia", List.IMPLICIT);
	}
	
	private void appendEvents(Vector eventIds) {
		Enumeration e = eventIds.elements();
		
		while(e.hasMoreElements()) {
			append("Zdarzenie " + e.nextElement(), null);
		}
	}
	
	public void commandAction(Command command, Displayable displayable) {
		switch(command.getCommandType()) {
			case Command.SCREEN:
				Vector events = (Vector)controller.getFromCache(CacheKey.EVENTS);
				Long eventId = (Long)events.elementAt(getSelectedIndex());
				CameraPreview cameraPreviewCanvas = (CameraPreview)controller.getApplicationScreen(ScreenType.PREVIEW);
				
				cameraPreviewCanvas.setEventId(eventId);
				
				controller.setCurrentDisplay(cameraPreviewCanvas);
				
				cameraPreviewCanvas.play();
				
				break;
			case Command.BACK:
				controller.setCurrentDisplay(ScreenType.MAIN_MENU);
				break;
		}
	}

	public void onThreadEnd() {
		Vector events = eventsLoader.getEventIds();
		
		controller.putToCache(CacheKey.EVENTS, events);
		
		appendEvents(events);
	}

	public void onThreadException(Exception e) {
		//TODO zaimplementowac
		e.printStackTrace();
	}

	public void setController(ApplicationController controller) {
		this.controller = controller;
	}

	public void setHttpConnector(HttpConnector connector) {
		this.connector = connector;
	}

	public void initialize() {
		Vector events = (Vector)controller.getFromCache(CacheKey.EVENTS);
		
		eventsLoader = new EventsLoaderThread(connector, this);

		if(events == null) {
			eventsLoader.start();
		}
		else {
			appendEvents(events);
		}
		
		addCommand(backCommand);
		
		setCommandListener(this);
	}

}
